package com.basicorm.db;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import com.basicorm.utils.StringUtils;

import db_java.Company;
import db_java.Person;

public class DbTestUtil {

    private final Connection connection;

    public DbTestUtil(Connection connection) {
        this.connection = connection;
    }

    public int countFromTable(String tableName) throws SQLException {
        Statement statement = connection.createStatement();
        statement.execute("select count(*) from " + tableName);
        ResultSet resultSet = statement.getResultSet();
        resultSet.next();
        return resultSet.getInt(1);
    }

    public void createTable(String tableDef) throws SQLException { // TODO VM add table definition
        connection.createStatement().executeUpdate(tableDef);
    }
    
    public String select(String query) throws SQLException{
    	Statement statement = connection.createStatement();
    	statement.execute(query);
    	ResultSet resultSet = statement.getResultSet();
    	Collection<String> resultList = new LinkedList<String>();
    	while (resultSet.next()) { 
    		Collection<String> row = new LinkedList<String>();
    		for (int i = 1; i<=resultSet.getMetaData().getColumnCount(); i++) {
    			row.add(resultSet.getString(i));
    		}
    		resultList.add(StringUtils.join( ", ", row));
    	}
    	return StringUtils.join( ";", resultList);
    }
    

	public static Connection getConnection() throws SQLException {
        return DriverManager.getConnection(
                "jdbc:hsqldb:mem:myunittests",
                "",
                "");
    }
	

	public void dropTable(String tableName) throws SQLException {
		connection.createStatement().executeUpdate("drop table if exists " + tableName);
	}
	
	public void dropSequence(String seqName) throws SQLException {
		connection.createStatement().executeUpdate("drop sequence if exists " + seqName);
	}
}
